from flask import Flask, render_template, jsonify, request, session
import random
from datetime import datetime

app = Flask(__name__)
app.secret_key = 'memory_card_game_secret_key_2024'

# 游戏配置
GAME_CONFIG = {
    'total_cards': 6,  # 总卡牌数
    'show_time': 3000,  # 展示时间（毫秒）
    'max_attempts': 3   # 最大尝试次数
}

# 卡牌图案数据
CARD_PATTERNS = [
    {'emoji': '🌟', 'name': '星星'},
    {'emoji': '🎈', 'name': '气球'},
    {'emoji': '🌈', 'name': '彩虹'},
    {'emoji': '🎨', 'name': '画笔'},
    {'emoji': '🎭', 'name': '面具'},
    {'emoji': '🎪', 'name': '马戏团'},
    {'emoji': '🎯', 'name': '靶子'},
    {'emoji': '🎲', 'name': '骰子'},
    {'emoji': '🎸', 'name': '吉他'},
    {'emoji': '🎺', 'name': '小号'},
    {'emoji': '🥁', 'name': '鼓'},
    {'emoji': '🎻', 'name': '小提琴'}
]

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/api/start_game', methods=['POST'])
def start_game():
    """开始新游戏"""
    difficulty = request.json.get('difficulty', 'easy')

    # 根据难度设置卡牌数量
    if difficulty == 'easy':
        card_count = 4
    elif difficulty == 'medium':
        card_count = 6
    else:  # hard
        card_count = 8

    # 随机选择卡牌
    selected_patterns = random.sample(CARD_PATTERNS, card_count)

    # 生成随机位置
    cards = []
    positions = list(range(card_count))
    random.shuffle(positions)

    for i, pattern in enumerate(selected_patterns):
        cards.append({
            'id': i,
            'pattern': pattern,
            'position': positions[i],
            'is_flipped': False
        })

    # 保存游戏状态到session
    session['game_state'] = {
        'cards': cards,
        'score': 0,
        'attempts': 0,
        'game_phase': 'memorizing',  # memorizing, testing, game_over
        'start_time': datetime.now().isoformat()
    }

    return jsonify({
        'success': True,
        'cards': cards,
        'show_time': GAME_CONFIG['show_time'],
        'difficulty': difficulty
    })

@app.route('/api/flip_cards', methods=['POST'])
def flip_cards():
    """翻转所有卡牌到背面"""
    if 'game_state' not in session:
        return jsonify({'success': False, 'error': '游戏未开始'})

    game_state = session['game_state']
    game_state['game_phase'] = 'testing'

    # 翻转所有卡牌到背面
    for card in game_state['cards']:
        card['is_flipped'] = True

    session['game_state'] = game_state

    return jsonify({
        'success': True,
        'game_phase': 'testing'
    })

@app.route('/api/check_card', methods=['POST'])
def check_card():
    """检查选择的卡牌是否正确"""
    if 'game_state' not in session:
        return jsonify({'success': False, 'error': '游戏未开始'})

    data = request.json
    card_id = data.get('card_id')
    guessed_position = data.get('guessed_position')

    game_state = session['game_state']

    if game_state['game_phase'] != 'testing':
        return jsonify({'success': False, 'error': '游戏阶段不正确'})

    # 查找选中的卡牌
    selected_card = None
    for card in game_state['cards']:
        if card['id'] == card_id:
            selected_card = card
            break

    if not selected_card:
        return jsonify({'success': False, 'error': '卡牌不存在'})

    # 检查位置是否正确
    is_correct = selected_card['position'] == guessed_position
    game_state['attempts'] += 1

    if is_correct:
        game_state['score'] += 10
        result_message = f"正确！{selected_card['pattern']['name']}确实在位置{guessed_position}"
    else:
        result_message = f"错误！{selected_card['pattern']['name']}不在位置{guessed_position}"

    # 检查游戏是否结束
    max_attempts = GAME_CONFIG['max_attempts']
    if game_state['attempts'] >= max_attempts:
        game_state['game_phase'] = 'game_over'

    session['game_state'] = game_state

    return jsonify({
        'success': True,
        'is_correct': is_correct,
        'message': result_message,
        'correct_position': selected_card['position'],
        'score': game_state['score'],
        'attempts': game_state['attempts'],
        'game_phase': game_state['game_phase']
    })

@app.route('/api/game_state', methods=['GET'])
def get_game_state():
    """获取当前游戏状态"""
    if 'game_state' not in session:
        return jsonify({'success': False, 'error': '游戏未开始'})

    return jsonify({
        'success': True,
        'game_state': session['game_state']
    })

@app.route('/api/leaderboard', methods=['GET', 'POST'])
def leaderboard():
    """排行榜功能"""
    if request.method == 'GET':
        # 获取排行榜数据
        # 这里简化处理，实际项目中应该使用数据库
        scores = [
            {'name': '小明', 'score': 80, 'date': '2024-11-20'},
            {'name': '小红', 'score': 75, 'date': '2024-11-19'},
            {'name': '小华', 'score': 70, 'date': '2024-11-18'}
        ]
        return jsonify({'success': True, 'scores': scores})

    else:  # POST
        # 提交分数
        data = request.json
        name = data.get('name', '匿名玩家')
        score = data.get('score', 0)

        # 这里应该保存到数据库
        # 简化处理，直接返回成功
        return jsonify({'success': True, 'message': '分数已提交'})

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=21111)